#ifndef SPLITTOOL_H
#define SPLITTOOL_H

#include <QGraphicsItem>
#include <QPainter>
#include <QPainterPath>
#include <QRectF>

#include "abstracttool.h"

// the split line for UI
class SplitLine : public QGraphicsItem {
 public:
  SplitLine();
  ~SplitLine();

  QPolygonF &line();
  // QGraphicsItem functions
  QRectF boundingRect() const;
  QPainterPath shape() const;
  void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
             QWidget *widget);

 private:
  QPolygonF *m_line;
};

// structure of the intersection point
struct CrossNode {
  QPointF crossPoint;  // intersection point
  int polyPointId1;    // edge point1 of the polygon
  int polyPointId2;    // edge point2 of the polygon
  int linePointId1;    // edge point1 of the line
  int linePointId2;    // edge point2 of the line
};

// class of splitting a polygon by a polyline
class Split {
 public:
  QVector<QPolygonF> split(QPolygonF &polygon, QPolygonF &line);

 private:
  bool intersect(QPointF &crossPoint, const QPointF &polyPoint1,
                 const QPointF &polyPoint2, const QPointF &linePoint1,
                 const QPointF &linePoint2);
  bool isBetween(const QPointF &p0, const QPointF &p1,
                 const QPointF &p2);  // if p0 is between p1 and p2
  QPolygonF *m_polygon;
  QPolygonF *m_polyLine;
  QVector<CrossNode> m_crossNodes;
};

class SplitTool : public AbstractTool {
 public:
  SplitTool(DocumentView *parent);
  ~SplitTool();

  virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
  virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
  virtual void keyPressEvent(QKeyEvent *event) { Q_UNUSED(event) };
  virtual void keyReleaseEvent(QKeyEvent *event) { Q_UNUSED(event) };

 private:
  SplitLine *m_splitLine;
  bool m_start;
  bool m_isCreating;
};

#endif  // SPLITTOOL_H
